var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
const moment = require('moment');
const { getAll } = require('../db');
let rootPath = path.dirname(__dirname);
const { debug } = require('../config');

const day = moment().format('M-D');
const month = moment().format('Y-M');

let oneMonthTime = 1000 * 24 * 60 * 60 * 30;
let oneDayTime = 1000 * 24 * 60 * 60;

const months = {};
for (let i = 11; i >= 0; i--) {
  let key = moment(moment(moment().startOf('month') - i * oneMonthTime)).format(
    'Y-M'
  );
  months[key] = 0;
}
// console.log(months);
const days = {};
for (let i = 30; i >= 0; i--) {
  let key = moment(moment(moment().startOf('day') - i * oneDayTime)).format(
    'M-D'
  );
  // console.log(moment(moment(moment().format('Y-M-D')) - i * oneDayTime));
  days[key] = 0;
}
// 抽象出来的一个方法
function getArr(event_type, obj, keys) {
  return Object.keys(keys).map((item) => {
    return {
      type: event_type,
      day: item,
      count: obj[event_type][item],
    };
  });
}

// 事件统计随时间
router.get('/statistic', async function (req, res) {
  let { status } = req.query;
  let sql = `select event_type,event_time from event where event_status=2 order by event_time`;
  console.log(sql);
  try {
    const resultDay = {
      刮擦: { ...days },
      碰撞: { ...days },
      追尾: { ...days },
      其它: { ...days },
    };
    const resultMonth = {
      刮擦: { ...months },
      碰撞: { ...months },
      追尾: { ...months },
      其它: { ...months },
    };
    const data = await getAll(sql);
    data.forEach((item) => {
      if (moment() - moment(item.event_time) < 30 * oneDayTime) {
        if (resultDay[item.event_type]) {
          resultDay[item.event_type][moment(item.event_time).format('M-D')]++;
        }
      }
      if (moment() - moment(item.event_time) < 12 * oneMonthTime) {
        if (resultDay[item.event_type]) {
          resultMonth[item.event_type][moment(item.event_time).format('Y-M')]++;
        }
      }
    });
    const result = {};
    result.day = [];
    result.month = [];
    Object.keys(resultDay).forEach((event_type) => {
      result.day.push(...getArr(event_type, resultDay, days));
    });
    Object.keys(resultMonth).forEach((event_type) => {
      result.month.push(...getArr(event_type, resultMonth, months));
    });

    res.send({
      code: 0,
      message: '',
      result,
    });
  } catch (err) {
    res.send({
      code: 500,
      message: '',
      result: debug ? '' : err,
    });
  }
});
module.exports = router;
